import json
import random
import sys
import time
from datetime import datetime

from selenium import webdriver
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.wait import WebDriverWait
from webdriver_manager.chrome import ChromeDriverManager
import requests
from bs4 import BeautifulSoup


class LianJia:
    def __init__(self):
        self.url = 'https://cd.lianjia.com/ershoufang/rs/'
        self.path = '/eoffice10/client/web/login'
        self.dir = ''
        self.driver = ''
        self.config()
        self.logDir = './log.txt'

    def config(self):
        try:
            chrome = ChromeDriverManager().install()

            self.driver = chrome
            self.dir = (sys.argv[0].split("\\"))
            self.dir.pop()
            self.dir = "\\".join(self.dir) + '\\'

            # f = open(self.dir + 'config.txt', 'r')
            # config = json.loads(f.read())
            # self.url = config['url']
            # f.close()
        except Exception as e:
            self.outLog(e)

    def begin(self):
        try:
            options = webdriver.ChromeOptions()
            options.add_argument('--headless')

            driver = webdriver.Chrome(self.driver, chrome_options=options)
            driver.get(self.url)

            html = driver.page_source
            # print(text)
            wait = WebDriverWait(driver, 5)

            self.parse(html)

            # wait.until(EC.presence_of_element_located((By.CLASS_NAME, 'sign-button')))

        except (Exception, TimeoutException) as e:
            self.outLog(e)

    def parse(self, html):
        soup = BeautifulSoup(html, 'html.parser')
        list = soup.find_all('ul.sellListContent > .LOGCLICKDATA')


    def outLog(self, line):
        e = str(line)

        # print(e)
        if isinstance(e, str):
            f = open(self.dir + self.logDir, 'w')
            f.write(e)
            f.close()
        else:
            print(line)

    def checkDay(self):

        today = datetime.now().today()
        year = today.strftime('%Y')
        month = today.strftime('%Y%m')
        day = today.strftime('%Y%m%d')

        url = 'https://api.apihubs.cn/holiday/get?year=' + year + '&month=' + month + '&date=' + day + '&cn=1&size=1'
        content = requests.get(url)
        content = content.content.decode('UTF8')
        content = json.loads(content)
        workday_cn = content['data']['list'][0]['workday_cn']

        if workday_cn != '工作日':
            self.week = True


if __name__ == '__main__':
    tt = LianJia()
    tt.begin()
